package com.example.memosystem.controller;

import com.example.memosystem.model.User;
import com.example.memosystem.service.UserService;
import com.example.memosystem.util.PasswordValidator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;

@Controller
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @GetMapping("/")
    public String index() {
        return "redirect:/login";
    }
    
    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }

    @PostMapping("/register")
    public String register(User user, Model model) {
        if (!PasswordValidator.isValidPassword(user.getPassword())) {
            model.addAttribute("error", "密码必须包含字母、数字和特殊字符，且长度不少于8位");
            return "register";
        }
        boolean success = userService.register(user);
        if (success) {
            return "redirect:/login?registered=true";
        } else {
            model.addAttribute("error", "用户名已存在");
            return "register";
        }
    }
    
    @GetMapping("/login")
    public String loginPage(@RequestParam(required = false) Boolean registered, Model model) {
        if (registered != null && registered) {
            model.addAttribute("message", "注册成功，请登录");
        }
        return "login";
    }
    
    @PostMapping("/login")
    public String login(@RequestParam String username, @RequestParam String password, 
                        HttpSession session, Model model) {
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("user", user);
            return "redirect:/memo/list";
        } else {
            model.addAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }
    
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
}